import React, { PureComponent, Fragment } from 'react';
import {
  Form,
  Input,
  Select,
  Modal,
  Radio, Icon, Upload, DatePicker,
} from 'antd';
import { phone, email } from '@/utils/regular';
import { connect } from 'dva';

const FormItem = Form.Item;
import moment from 'moment';

const RadioGroup = Radio.Group;


@connect(({ packing }) => ({
  packing,
}))
@Form.create()
class UpdateForm extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      iconList: [],
    };
    this.formLayout = {
      labelCol: { span: 7 },
      wrapperCol: { span: 13 },
    };
  }

  handleChange = (type, info) => {
    let logoList = info;
    logoList = logoList.map((file) => {
      if (file.response) {
        file.url = file.response.url;
      }
      return file;
    });

    logoList = logoList.filter((file) => {
      if (file.response) {
        return file.response.status === 'success';
      }
      return true;
    });
    if (type === 'logo') {
      this.setState({ logoList });
    } else {
      this.setState({ iconList: logoList });
    }
  };
  iconCustomRequest = (componentsData) => {
    let _this = this;
    const { dispatch, form } = this.props;
    let originFile = componentsData.file;
    const formData = new FormData();
    formData.append('multipartFile', originFile);
    formData.append('name', originFile.name);
    formData.append('uid', originFile.uid);
    dispatch({
      type: 'global/upload',
      payload: formData,
      callback(res) {
        if (res.code === 200) {
          let obj = {
            ...res.msg,
          };
          form.setFieldsValue({
            bannerImg: res.msg.url,
          });
          _this.handleChange('icon', [obj]);
        }
      },
    });


  };
  // 表单
  renderContent = () => {
    const { form, values } = this.props;
    const { iconList } = this.state;
    const iconProps = {
      action: `/img/upload`,
      showUploadList: { showPreviewIcon: true, showRemoveIcon: false },

      multiple: false,
      customRequest: this.iconCustomRequest,
      listType: 'picture-card',
      className: 'upload-list-inline',
    };
    return [
      <FormItem key="bannerName" {...this.formLayout} label="名称">
        {form.getFieldDecorator('bannerName', {
          rules: [{ required: true, message: '请输入名称！' }],
          initialValue: values.bannerName,
        })(<Input placeholder="请输入"/>)}
      </FormItem>,
      <FormItem key="bannerImg" {...this.formLayout} label="图片">
        {
          iconList.length > 0 ?
            form.getFieldDecorator('bannerImg', {
              rules: [{ required: true, message: '请上传banner！' }],
              initialValue: values.bannerImg,
            })(
              <Upload {...iconProps} fileList={iconList}>
                <Icon type="upload"/> 上传
              </Upload>,
            ) : form.getFieldDecorator('bannerImg', {
              rules: [{ required: true, message: '请上传banner！' }],
              initialValue: values.bannerImg,
            })(
            <Upload {...iconProps} fileList={
              values.bannerImg ? [{
                name: values.bannerImg,
                uid: 1,
                url: values.bannerImg,
              }] : []
            }>
              <Icon type="upload"/> 上传
            </Upload>,
            )}
      </FormItem>,
      <FormItem key="status" {...this.formLayout} label="状态">
        {form.getFieldDecorator('status', {
          rules: [{ required: true, message: '请选择状态！' }],
          initialValue: values.status || 1,
        })(
          <RadioGroup>
            <Radio value={1}>启用</Radio>
            <Radio value={2}>停用</Radio>
          </RadioGroup>,
        )}
      </FormItem>,
      <FormItem key="type" {...this.formLayout} label="发布范围">
        {form.getFieldDecorator('type', {
          rules: [{ required: true, message: '请选择发布范围！' }],
          initialValue: values.type,
        })(
          <Select style={{ width: '100%' }}>
            <Option value={1}>移动</Option>
            <Option value={2}>PC</Option>
            <Option value={3}>全部</Option>
          </Select>,
        )}
      </FormItem>,

      <FormItem key="url" {...this.formLayout} label="跳转路径">
        {form.getFieldDecorator('url', {
          rules: [{ required: true, message: '请输入跳转路径！' }],
          initialValue: values.url,
        })(<Input placeholder="请输入"/>)}
      </FormItem>,

      <FormItem key="startTime" {...this.formLayout} label="生效时间">
        {form.getFieldDecorator('startTime', {
          rules: [{ required: false, message: '请选择生效时间！' }],
          initialValue: moment(values.startTime),
        })(<DatePicker placeholder="选择生效时间"
                       style={{ width: '100%' }}/>)}
      </FormItem>,
      <FormItem key="endTime" {...this.formLayout} label="失效时间">
        {form.getFieldDecorator('endTime', {
          rules: [{ required: false, message: '请选择失效时间！' }],
          initialValue: moment(values.endTime),
        })(<DatePicker placeholder="选择失效时间"
                       style={{ width: '100%' }}/>)}
      </FormItem>,
    ];
  };

  //弹窗
  render() {
    const { updateModalVisible, handleUpdateModalVisible, modalVisible } = this.props;
    //完成
    const handleNext = () => {
      const { form, values, handleUpdate, handleAdd, modalVisible } = this.props;
      form.validateFields((err, fieldsValue) => {
        if (err) return;
        const formVals = { ...values, ...fieldsValue };
        formVals.endTime = fieldsValue.endTime ? moment(fieldsValue.endTime).format('YYYY-MM-DD') : '';
        formVals.startTime = fieldsValue.startTime ? moment(fieldsValue.startTime).format('YYYY-MM-DD') : '';
        formVals.jumpType = 1;
        if (modalVisible) {
          handleAdd(formVals);
        } else {
          handleUpdate(formVals);

        }
      });
    };
    return (
      <Modal
        width={640}
        bodyStyle={{ padding: '32px 40px 48px' }}
        destroyOnClose
        title={modalVisible ? '新增Banner' : '修改Banner'}
        visible={updateModalVisible}
        onOk={handleNext}
        onCancel={() => handleUpdateModalVisible(false, [])}
      >
        {this.renderContent()}
      </Modal>
    );
  }
}

export default UpdateForm;
